﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Threading.Tasks;
using SmsUI.DataBase.smsdbDataSetTableAdapters;

namespace SmsUI
{
    public partial class sendListForm : DevExpress.XtraEditors.XtraUserControl
    {
        private string detectFile = "c:\\detectFile.txt";
        DataBase.smsdbDataSet.tb_SendListDataTable tb
        {
            get
            {
                return DbRules.Instance.GetSendListTable();
            }
        }
        //  public static object sendListLock = new object();
        public sendListForm()
        {
            InitializeComponent();
            ItemsSource = new List<ListViewItem>();
            CurrentCacheItemsSource = new List<ListViewItem>();
            dataStates.Text = "已完成";
            LoadNum();
        }

        void lsvSendList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            if (this.CurrentCacheItemsSource == null || this.CurrentCacheItemsSource.Count == 0)
            {
                return;
            }

            e.Item = this.CurrentCacheItemsSource[e.ItemIndex];
            if (e.ItemIndex == this.CurrentCacheItemsSource.Count)
            {
                this.CurrentCacheItemsSource = null;
            }
        }
        protected List<ListViewItem> ItemsSource
        {
            get;
            private set;
        }

        private static readonly object listViewLock = new object();

        public void AddNum(string num, string port, string content)
        {
            if (!string.IsNullOrEmpty(num))
            {

                SendClass sc = null;
                if (!string.IsNullOrEmpty(port))
                {
                    sc = new SendClass() { ComPort = port, Content = content };
                }
                ListViewItem item = new ListViewItem { Text = num, Tag = sc };
                lock (listViewLock)
                {
                    CurrentCacheItemsSource.Insert(0, item);
                    Invalidat();

                }



            }
        }
        private void btnInput_Click(object sender, EventArgs e)
        {

            InputNum win = new InputNum("请输入号码：");

            win.ShowDialog();
            if (win.DialogResult == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(win.PhoneNum))
                {
                    lock (listViewLock)
                    {

                        ListViewItem item = new ListViewItem { Text = win.PhoneNum, Tag = null };

                        CurrentCacheItemsSource.Insert(0, item);
                        Invalidat();


                    }


                }
            }


        }



        private void btnIn_Click(object sender, EventArgs e)
        {

            OpenFileDialog opendlg = new OpenFileDialog();
            opendlg.Title = "打开文本文件";
            opendlg.Filter = "文本文件 (*.txt)|*.txt";
            if (opendlg.ShowDialog() == DialogResult.OK)
            {

                string filename = opendlg.FileName;

                TxtInList(filename);

            }

        }
        protected List<ListViewItem> CurrentCacheItemsSource
        {
            get;
            private set;
        }
        private void LoadListViewItems(List<ListViewItem> items)
        {
            lsvSendList.Items.Clear();
            if (items == null)
            {
                stripStatusInfo.Text = "当前总共记录数为：0";
                return;
            }


            lsvSendList.Scrollable = true;

            lsvSendList.Visible = true;

            lsvSendList.VirtualListSize = items.Count;

            lsvSendList.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(lsvSendList_RetrieveVirtualItem);
            lsvSendList.VirtualListSize = items.Count;//设置虚拟列表容量大小
            lsvSendList.VirtualMode = true;
            stripStatusInfo.Text = "当前总共记录数为：" + items.Count;
        }

        public Label InputStatesLable
        {
            get
            {
                return dataStates;
            }
        }
        public void TxtInList(string filename)
        {
            string strLine;

            lock (listViewLock)
            {

                try
                {
                    //  lsvSendList.SuspendLayout();
                    //   lsvSendList.BeginUpdate();

                    // lsvSendList.BeginUpdate();

                    using (FileStream aFile = new FileStream(filename, FileMode.Open, FileAccess.Read))
                    {
                        using (StreamReader sr = new StreamReader(aFile))
                        {

                            strLine = sr.ReadLine();
                            while (strLine != null)
                            {
                                strLine = strLine.Trim();
                                if (!string.IsNullOrEmpty(strLine))
                                {

                                    //int num= qta.InsertOneNumer(strLine, 5, "", "", "0");
                                    //    tb.Addtb_SendListRow(strLine, 5, "", "", "0");
                                    CurrentCacheItemsSource.Add(new ListViewItem() { Text = strLine, Tag = null });

                                }

                                strLine = sr.ReadLine();
                            }

                        }

                    }


                    //  lsvSendList.EndUpdate();
                    // lsvSendList.ResumeLayout(true);
                    // dataStates.Text = "正在更新";
                    // updateSendListTask = new Task(() => DbRules.Instance.UpdateSendList());
                    //  updateSendListTask.Start();
                    //   Action<Task> finish = (aa) => this.BeginInvoke(new System.Windows.Forms.MethodInvoker(() =>
                    //  dataStates.Text = "已完成"));
                    //updateSendListTask.ContinueWith(finish);
                    //
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    DevExpress.XtraEditors.XtraMessageBox.Show(ex.ToString());

                    return;
                }
                Invalidat();
            }

        }
        public void ExportNum()
        {

            SaveFileDialog opendlg = new SaveFileDialog();
            opendlg.Title = "导出发送号码";
            opendlg.Filter = "文本文件 (*.txt)|*.txt";
            if (opendlg.ShowDialog() == DialogResult.OK)
            {

                string filename = opendlg.FileName;
                try
                {
                    //  lsvSendList.SuspendLayout();
                    //   lsvSendList.BeginUpdate();

                    // lsvSendList.BeginUpdate();

                    using (FileStream aFile = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        using (StreamWriter sr = new StreamWriter(aFile))
                        {
                            for (int i = 0; i < tb.Count; i++)
                            {
                                sr.WriteLine(tb[i].PhoneNum);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("导出号码错误!" + ex.ToString());
                }
            }

        }
        private void btnClear_Click(object sender, EventArgs e)
        {


            if (DevExpress.XtraEditors.XtraMessageBox.Show("确认要清空列表嘛？", "清空 ", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation).Equals(DialogResult.OK))
            {
                lock (listViewLock)
                {
                    CurrentCacheItemsSource.Clear();
                    Invalidat();
                }
                lock (SmsHelper.SmsHelper.DicLock)
                {
                    SmsHelper.SmsHelper.Instance.QueueOutMessageDic.Clear();
                }

            }

            //DeleteItem(lsvSendList.Items);
        }


        public void Invalidat()
        {
            lsvSendList.VirtualListSize = CurrentCacheItemsSource.Count;
            lsvSendList.Invalidate();
            stripStatusInfo.Text = "当前总共记录数为：" + CurrentCacheItemsSource.Count;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            lock (GetNumLock)
            {
                for (int i = 0; i < lsvSendList.SelectedIndices.Count; i++)
                {
                    this.CurrentCacheItemsSource.Remove(lsvSendList.SelectedItems[i]);
                }
                Invalidat();
            }
        }
        private static object GetNumLock = new object();
        public SendClass GetANum()
        {
            SendClass sc = new SendClass();
            sc.PhoneNum = "";
            sc.ComPort = "";

            this.Invoke(new MethodInvoker(() =>
            {
                ListViewItem item = null;
                lock (GetNumLock)
                {
                    for (int i = 0; i < CurrentCacheItemsSource.Count; i++)
                    {
                        item = CurrentCacheItemsSource[i];
                        if (item.Tag != null)
                        {
                            sc = (SendClass)item.Tag;

                        }

                        sc.PhoneNum = item.Text;
                        CurrentCacheItemsSource.Remove(item);
                        Invalidat();
                        break;
                    }
                }
            }));

            return sc;
        }
        private void sendListForm_Load_1(object sender, EventArgs e)
        {
            
        }
        void LoadNum()
        {
            try
            {
                FileStream aFile = new FileStream(detectFile, FileMode.Open, FileAccess.Read);
                using (StreamReader sr = new StreamReader(aFile))
                {
                    string strLine = sr.ReadLine();

                    while (strLine != null)
                    {
                        strLine.Trim();

                        this.ItemsSource.Add(new ListViewItem(strLine));
                        strLine = sr.ReadLine();
                    }
                }
            }
            catch
            {
            }

            CurrentCacheItemsSource = ItemsSource;
            LoadListViewItems(CurrentCacheItemsSource);
        }
        public void SaveUnSendNum()
        {
            try
            {
                File.Delete(detectFile);
            }
            catch
            {
            }
            FileStream aFile = new FileStream(detectFile, FileMode.OpenOrCreate, FileAccess.Write);
            string strLine = "";
            using (StreamWriter sw = new StreamWriter(aFile))
            {
                foreach (ListViewItem it in this.CurrentCacheItemsSource)
                {
                    strLine = it.Text;
                    //读下一行
                    sw.WriteLine(strLine);
                }
            }

        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportNum();
        }


    }
}
